import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";

// 普通加载
// import Home from "../pages/Home.vue";
// import About from "../pages/About.vue";

// 懒加载
const Home = () =>
  import(/* webpackChunkName: "Home-chunk" */ "../pages/Home.vue");
const HomeMessage = () => import("../pages/HomeMessage.vue");
const HomeShop = () => import("../pages/HomeShops.vue");
const HomeMoment = () => import("../pages/HomeMoment.vue");

const About = () => import("../pages/About.vue");
const User = () => import("../pages/User.vue");
const NotFound = () => import("../pages/NotFound.vue");
const Category = () => import("../pages/Category");
const Login = () => import("../pages/Login.vue");

// 配置映射关系
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    name: "home",
    path: "/home",
    component: Home,
    children: [
      // 默认路径
      {
        path: "",
        redirect: "/home/message",
      },
      {
        path: "message",
        component: HomeMessage,
      },
      {
        path: "shops",
        component: HomeShop,
      },
    ],
  },
  {
    path: "/about",
    component: About,
  },
  {
    path: "/user/:username",
    component: User,
  },
  {
    path: "/login",
    component: Login,
  },
  {
    path: "/:pathMatch(.*)*",
    component: NotFound,
  },
];

// 创建路由对象
const router = createRouter({
  routes,
  history: createWebHistory(),
});

// 动态增加路由
router.addRoute({
  path: "/category",
  component: Category,
});

// 增加二级路由对象
router.addRoute("home", {
  path: "moment",
  component: HomeMoment,
});

// 导航守卫
// to：即将进入的路由Route对象
// from：即将离开的路由Route对象
router.beforeEach((to, from) => {
  console.log("进行了路由跳转");
  // if (to.path.indexOf("/home") !== -1) {
  //   return "/login";
  // }

  if (to.path !== "/login") {
    const token = window.localStorage.getItem("token");

    if (!token) {
      return "/login";
    }
  }
});

export default router;
